import locale
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound
import datetime
import time
from django.core.exceptions import ValidationError
from decimal import Decimal, InvalidOperation
from django.template.context import RequestContext
from django.shortcuts import render_to_response
from django.views.generic.base import TemplateView
from settings import MEDIA_ROOT
from jrcmodel.models import EuroConv, ArchivePerf, DvRatio, ProfitLossesValues, MyConstants, CST 
from jrcmodel.models import Market, FuturesContractsAmount,FuturesTradesAmount
from django.contrib.auth.decorators import login_required, permission_required
from pet.models import RfiPor1, RfiPor3, EuroConvDaily, Deviation
from pet.models import MyUploadFileForm, EuroConvDailyUploadForm
from django.views.generic.dates import ArchiveIndexView
from django.views.generic.edit import CreateView, DeleteView, UpdateView
from django.forms.models import ModelForm
from django.forms.extras.widgets import SelectDateWidget
from django.views.generic.list import ListView
from jrcshared.models import JrcPermission
from tracking.models import MonthYearLinks

class IndexView(TemplateView):
    template_name = "pet/index.html"

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        dates = [(2011, 10), (2011, 11), (2011, 12)]
        for y in range(2012, datetime.datetime.now().year + 1):
            for m in range(1, 13):
                dates += (y, "{0:02}".format(m)),
        context["dates"] = dates
        return context

class ListDeviationsView(ListView):
    template_name = "deviation_list.html"
    def get_queryset(self):
        return Deviation.objects.all()

class CreateDeviationView(CreateView):
    model = Deviation
    template_name = "deviation_form.html"
    success_url = "/pet/deviations/"

class UpdateDeviationView(UpdateView):
    model = Deviation
    template_name = "deviation_form.html"
    success_url = "/pet/deviations/"    

class DeleteDeviationView(DeleteView):
    model = Deviation
    template_name = "deviation_confirm_delete.html"
    success_url = "/pet/deviations/"

# TODO: move to models.py
class EuroConvDailyForm(ModelForm):
    class Meta:
        model = EuroConvDaily
        widgets = {
            "date": SelectDateWidget()
        }

class EuroConvDailyCreateView(CreateView):
    model = EuroConvDaily
#    template_name
    success_url = "/pet/euroconv/daily/"
    
#    def get_context_data(self, **kwargs):
#        context = super(CreateView, self).get_context_data(**kwargs)
#        context["form"] = EuroConvDailyForm()
#        return context

class EuroConvDailyDeleteView(DeleteView):
    """
    Generic class to delete from DB
    """
    model = EuroConvDaily
    success_url = "/pet/euroconv/daily/"
    template_name = "pet/euroconvdaily_confirm_delete.html"

class EuroConvDailyUpdateView(UpdateView):
    model = EuroConvDaily
    success_url = "/pet/euroconv/daily/"
    
    def get_context_data(self, **kwargs):
        context = super(UpdateView, self).get_context_data(**kwargs)
#        if self.request.method == "POST":
#            form = EuroConvDailyForm(self.request.POST, self.request.FILES)
#            form.save()
#            return HttpResponseRedirect("/pet/euroconv/daily/")
#        else:
#            form = EuroConvDailyForm(instance = self.object)
#            context["form"] = form
        return context
    
class EuroConvDailyListView(ListView):
#    model = EuroConvDaily
    template_name = "pet/euroconvdaily_list.html"
#    queryset = EuroConvDaily.objects.all().order_by("date")
    
    def get_context_data(self, **kwargs):
        context = super(ListView, self).get_context_data(**kwargs)
        context["month_year_link"] = MonthYearLinks("/pet/euroconv/daily/", self.request)
        return context
    
    def get_queryset(self):
        year = 0
        month = 0
        try:
            year = int(self.request.GET.get("year"))
        except:
            year = datetime.datetime.now().year
        try:
            month = int(self.request.GET.get("month"))
        except:
            month = datetime.datetime.now().month
        print "Date: %d-%d" % (year, month)
        month_len = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0]
        date_to = "%d-%d-%d" % (year, month, month_len[month])
        print "Date to: %s" % date_to
        return EuroConvDaily.objects.all().filter(date__gte = "%d-%d-01" % (year, month)).filter(date__lte = date_to)


class EuroConvMonthView(ArchiveIndexView):
#    model = EuroConvDaily
    allow_empty = True
    queryset = EuroConvDaily.objects.all()
    month_format = "%m"
#    year = 2011
    month = 1
    date_field = "date"

@login_required
def rfi_pro3(request):
    current_year = datetime.datetime.now().year
    
    if request.method == "POST":
        year = request.POST.get("year")
    else:
        year = request.GET.get("year")
    print "Year from request: %s" % year
    if year != None:
        year = int(year)
    else:
        year = current_year
#    print "Year is %s" % year
    
    year_prev = year - 1
    year_next = 0
    # Whether it is possible to go next year
    if year <= current_year:
        year_next = year + 1 

    if request.method == "POST":
        ar_values = RfiPor3.objects.filter(year = year)
        ar_values.delete()
        
        for m in range(1, 13):
            item = RfiPor3()
            item.year = year
            item.month = m
            v = request.POST.get("v_%d" % m)
            print "Saving value: %s" % v
            
            try:
                item.value = Decimal(v)
            except (ValidationError, InvalidOperation):
                print "ERROR saving value [%s]" % v
                item.value = 0.0
#            print item
            item.save()
        
        return HttpResponseRedirect("/pet/rfipor3?year=%d" % year)

    ar_values = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    ar = RfiPor3.objects.filter(year = year).order_by("month")
    print "Default array: %s" % ar_values
    print "From DB: %s" % ar
    for i in ar:
        ar_values[i.month - 1] = i.value
    print ar_values
    
    return render_to_response(
                              "pet/rfipor.html"
                              , {
                                 "months": range(1, 13)
                                 , "name": "POR3"
                                 , "linkto": "/pet/rfipor3/"
                                 , "ar_values": ar_values
                                 , "year": year
                                 , "year_prev": year_prev
                                 , "year_next": year_next
                                 }
                              , context_instance = RequestContext(request))

        
@login_required
def rfi_pro1(request):
    current_year = datetime.datetime.now().year
    
    if request.method == "POST":
        year = request.POST.get("year")
    else:
        year = request.GET.get("year")
    print "Year from request: %s" % year
    if year != None:
        year = int(year)
    else:
        year = current_year
#    print "Year is %s" % year
    
    year_prev = year - 1
    year_next = 0
    # Whether it is possible to go next year
    if year <= current_year:
        year_next = year + 1 

    if request.method == "POST":
        ar_values = RfiPor1.objects.filter(year = year)
        ar_values.delete()
        
        for m in range(1, 13):
            item = RfiPor1()
            item.year = year
            item.month = m
            v = request.POST.get("v_%d" % m)
            print "Saving value: %s" % v
            
            try:
                item.value = Decimal(v)
            except (ValidationError, InvalidOperation):
                print "ERROR saving value [%s]" % v
                item.value = 0.0
#            print item
            item.save()
        
        return HttpResponseRedirect("/pet/rfipor1?year=%d" % year)

    ar_values = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    ar = RfiPor1.objects.filter(year = year).order_by("month")
#    print "Default array: %s" % ar_values
#    print "From DB: %s" % ar
    for i in ar:
        ar_values[i.month - 1] = i.value
#    print ar_values
    
    return render_to_response(
                              "pet/rfipor.html"
                              , {
                                 "months": range(1, 13)
                                 , "name": "POR1"
                                 , "linkto": "/pet/rfipor1/"
                                 , "ar_values": ar_values
                                 , "year": year
                                 , "year_prev": year_prev
                                 , "year_next": year_next
                                 }
                              , context_instance = RequestContext(request))

        
@login_required
def futures_contracts_amount(request):
    current_year = datetime.datetime.now().year
    
    if request.method == "POST":
        year = request.POST.get("year")
    else:
        year = request.GET.get("year")
    if year != None:
        year = int(year)
    else:
        year = current_year
#    print "Year is %s" % year
    
    year_prev = year - 1
    year_next = 0
    # Whether it is possible to go next year
    if year <= current_year:
        year_next = year + 1

    if request.method == "POST":
        csts = CST.objects.filter(market_direction_1__market_id__asset__name = "Futures").filter(status_id = MyConstants.STATUS_APPROVED)
        FuturesContractsAmount.objects.filter(year = year).delete()
        for cst in csts:
            for month in range(1, 13):
                item = FuturesContractsAmount()
                item.year = year
                item.month = month
                item.cst = cst
#                print "ex[%s][%d]" % (cst.slug_name(), month)
                item.amount = 0
                v = request.POST.get("ex[%s][%d]" % (cst.slug_name(), month))
#                print "value of it: %s" % v 
#                try:
                item.amount = int(v)
                item.save()
                print item
#                except Invali
        return HttpResponseRedirect("/pet/futurescontractsamount?year=%d" % year)

    # Select CSTs which belongs to Futures markets
    csts = CST.objects.filter(market_direction_1__market_id__asset__name = "Futures").filter(status_id = MyConstants.STATUS_APPROVED)
    ar_items = {}
    for cst in csts:
        ar_items[cst.name] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0]
        items = FuturesContractsAmount.objects.filter(year = year).filter(cst__pk = cst.pk).filter(status_id = MyConstants.STATUS_APPROVED).order_by("month")
        print "Market %s items: %s" % (cst.name, items)
        for i in items:
            ar_items[cst.name][i.month - 1] = i.amount

    return render_to_response(
                              "pet/futurescontractsamount.html"
                              , {
                                 "ar_items": ar_items
                                 , "ar_months": range(1, 13)
                                 , "year": year
                                 , "year_prev": year_prev
                                 , "year_next": year_next
                              }
                              , context_instance = RequestContext(request))

def get_futures_contracts_amount(request):
    year = request.GET.get("year")
    if year != None:
        year = int(year)
    else:
        year = datetime.datetime.now().year
        
    values = {}
    csts = CST.objects.filter(market_direction_1__market_id__asset__name = "Futures").filter(status_id = MyConstants.STATUS_APPROVED)
    print csts
    for cst in csts:
        values[cst.name] = ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"]
        items = FuturesContractsAmount.objects.filter(year = year).filter(cst__pk = cst.pk).filter(status_id = MyConstants.STATUS_APPROVED).order_by("month")
        for i in items:
            values[cst.name][i.month - 1] = "%d" % i.amount
    print values

    lines = []
    for key in values.keys():
        lines.append("\"%s\":[%s]" % (key, ",".join(values.get(key))))
        
    callback = request.GET.get("callback")
    if callback == None:
        body = "{%s}" % ",".join(lines)
    else:
        body = "%s({%s})" % (callback, ",".join(lines))
    return HttpResponse(body)



@login_required
def futures_trades_amount(request):
    current_year = datetime.datetime.now().year
    
    if request.method == "POST":
        year = request.POST.get("year")
    else:
        year = request.GET.get("year")
    if year != None:
        year = int(year)
    else:
        year = current_year
#    print "Year is %s" % year
    
    year_prev = year - 1
    year_next = 0
    # Whether it is possible to go next year
    if year <= current_year:
        year_next = year + 1

    if request.method == "POST":
        csts = CST.objects.filter(market_direction_1__market_id__asset__name = "Futures").filter(status_id = MyConstants.STATUS_APPROVED)
        FuturesTradesAmount.objects.filter(year = year).delete()
        for cst in csts:
            for month in range(1, 13):
                item = FuturesTradesAmount()
                item.year = year
                item.month = month
                item.cst = cst
                item.amount = 0
                print "ex[%s][%d]" % (cst.slug_name(), month)
                v = request.POST.get("ex[%s][%d]" % (cst.slug_name(), month))
                print "value of it: %s" % v 
                item.amount = int(v)
                item.save()
                print item
#                except Invali
        return HttpResponseRedirect("/pet/futurestradesamount?year=%d" % year)

    # Select CSTs which belongs to Futures markets
    csts = CST.objects.filter(market_direction_1__market_id__asset__name = "Futures").filter(status_id = MyConstants.STATUS_APPROVED)
    ar_items = {}
    for cst in csts:
        ar_items[cst.name] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0]
        items = FuturesTradesAmount.objects.filter(year = year).filter(cst__pk = cst.pk).filter(status_id = MyConstants.STATUS_APPROVED).order_by("month")
        print "Market %s items: %s" % (cst.name, items)
        for i in items:
            ar_items[cst.name][i.month - 1] = i.amount

    return render_to_response(
                              "pet/futurestradesamount.html"
                              , {
                                 "ar_items": ar_items
                                 , "ar_months": range(1, 13)
                                 , "year": year
                                 , "year_prev": year_prev
                                 , "year_next": year_next
                              }
                              , context_instance = RequestContext(request))

def get_futures_trades_amount(request):
    year = request.GET.get("year")
    if year != None:
        year = int(year)
    else:
        year = datetime.datetime.now().year
        
    values = {}
    csts = CST.objects.filter(market_direction_1__market_id__asset__name = "Futures").filter(status_id = MyConstants.STATUS_APPROVED)
    print csts
    for cst in csts:
        values[cst.name] = ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"]
        items = FuturesTradesAmount.objects.filter(year = year).filter(cst__pk = cst.pk).filter(status_id = MyConstants.STATUS_APPROVED).order_by("month")
        for i in items:
            values[cst.name][i.month - 1] = "%d" % i.amount
    print values

    lines = []
    for key in values.keys():
        lines.append("\"%s\":[%s]" % (key, ",".join(values.get(key))))
        
    callback = request.GET.get("callback")
    if callback == None:
        body = "{%s}" % ",".join(lines)
    else:
        body = "%s({%s})" % (callback, ",".join(lines))
    return HttpResponse(body)

def get_profit_losses(request):
    year = request.GET.get("year")
    if year != None:
        year = int(year)
    else:
        year = datetime.datetime.now().year
        
    asset_class = MyConstants.ASSET_CLASSES_CHOICES[0][1]
    v = request.GET.get("asset")
    if v == MyConstants.ASSET_CLASSES_CHOICES[1][1]:
        asset_class = v
    print "Asset class is: %s" % asset_class

    values = {}
    for market in Market.objects.filter(asset__name = asset_class).filter(status_id = MyConstants.STATUS_APPROVED):
        values[market.name] = ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"]
    print values

    items = ProfitLossesValues.objects.filter(year = year).filter(market__asset__name = asset_class)
    for i in items:
        print i
#        print "#%d %s" % (i.market.pk, i.market.name)
        if not values.has_key(i.market.name):
            values[i.market.name] = ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"]
        values[i.market.name][i.month - 1] = "%.1f" % i.value
        
    lines = []
    for key in values.keys():
        lines.append("\"%s\":[%s]" % (key, ",".join(values.get(key))))
        
    callback = request.GET.get("callback")
    if callback == None:
        body = "{%s}" % ",".join(lines)
    else:
        body = "%s({%s})" % (callback, ",".join(lines))
    return HttpResponse(body)

@login_required
def profit_losses(request):
    current_year = datetime.datetime.now().year
    
    if request.method == "POST":
        year = request.POST.get("year")
    else:
        year = request.GET.get("year")
    print "Year from request: %s" % year
    if year != None:
        year = int(year)
    else:
        year = current_year
#    print "Year is %s" % year
    
    year_prev = year - 1
    year_next = 0
    # Whether it is possible to go next year
    if year <= current_year:
        year_next = year + 1

    if request.method == "POST":
        markets = Market.objects.filter(status_id = MyConstants.STATUS_APPROVED)
        ProfitLossesValues.objects.filter(year = year).delete()
        for market in markets:
            for m in range(1, 13):
                item = ProfitLossesValues()
                item.year = year
                item.month = m
                item.market = market
#                item.asset_class = m.market.a 
#                item.cst_id = m.pk
                item.exchange_name = market.name
#                print "ex[%s][%d]" % (market.name, m)
                v = request.POST.get("ex[%s][%d]" % (market.name, m))
#                print "value of it: %s" % v
#                try:
                item.value = v
                item.save()
                print item
#                except Invali
        return HttpResponseRedirect("/pet/profitlosses?year=%d" % year)

    markets = Market.objects.filter(status_id = MyConstants.STATUS_APPROVED).order_by("asset")
    ar_profit_losses = {}
    for m in markets:
        ar_profit_losses[m.name] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0]
        items = ProfitLossesValues.objects.filter(year = year).filter(market__pk = m.pk).filter(status_id = MyConstants.STATUS_APPROVED).order_by("month")
        print "Market %s items: %s" % (m.name, items)
#        items = ProfitLossesValues.objects.filter(year = year).filter(exchange_name = m).order_by("month")
#        print items
        for i in items:
            ar_profit_losses[m.name][i.month - 1] = i.value

#    ar_profit_losses = {
#        "EURUSD-30": [23.1, -120, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0]
#        , "AUDJPY-120": [-139.6, -85.4, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0]
#        , "USDJPY-60": [74.6, 76.8, 97.2, 258.8, -183.3, -17.5, -72.5, 0, 0, 0, 0 ,0]
#        , "USDJPY-120": [0, 0, 163.8, 320.7, -148.2, -42, 73.5, 0, 0, 0, 0 ,0]
#        , "GBPJPY-60": [-16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0]
#        , "EURNZD-120": [279, -23.6, 53.6, 506.2, 259.3, 159.2, 361, 0, 0, 0, 0 ,0]                    
#    }
    return render_to_response(
                              "pet/profitlosses.html"
                              , {
                                 "ar_profits": ar_profit_losses
                                 , "ar_months": range(1, 13)
                                 , "year": year
                                 , "year_prev": year_prev
                                 , "year_next": year_next
                              }
                              , context_instance = RequestContext(request))
    

def get_dvratio(request):
    body = "{}"
    items = DvRatio.objects.all().order_by("year")
    ar_years = {}
    for r in items:
        if ar_years.has_key(r.year) == False:
            ar_years[r.year] = ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"]
        ar_years[r.year][r.month - 1] = "%.3f" % r.value

    lines = []
    for year in ar_years.keys():
        lines.append("\"%d\":[%s]" % (year, ",".join(ar_years[year])))

    callback = request.GET.get("callback")
    if callback != None:
        body = "%s({%s})" % (callback, ",".join(lines))
    else:
        body = "{%s}" % ",".join(lines) 
#        print year
    return HttpResponse(body, content_type="text/html")
        
@login_required
def dvratio(request):
    current_year = datetime.datetime.now().year
    
    if request.method == "POST":
        year = request.POST.get("year")
    else:
        year = request.GET.get("year")
    print "Year from request: %s" % year
    if year != None:
        year = int(year)
    else:
        year = current_year
#    print "Year is %s" % year
    
    year_prev = year - 1
    year_next = 0
    # Whether it is possible to go next year
    if year <= current_year:
        year_next = year + 1 

    if request.method == "POST":
        ar_values = DvRatio.objects.filter(year = year)
        ar_values.delete()
        
        for m in range(1, 13):
            item = DvRatio()
            item.year = year
            item.month = m
            v = request.POST.get("v_%d" % m)
            print "Saving value: %s" % v
            
            try:
                item.value = Decimal(v)
            except (ValidationError, InvalidOperation):
                print "ERROR saving value [%s]" % v
                item.value = 0.0
            item.save()
        
        return HttpResponseRedirect("/pet/dvratio?year=%d" % year)

    ar_values = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    ar = DvRatio.objects.filter(year = year).order_by("month")
    print "Default array: %s" % ar_values
    print "From DB: %s" % ar
    for i in ar:
        ar_values[i.month - 1] = i.value
    print ar_values
    
    return render_to_response(
                              "pet/dvratio.html"
                              , {
                                 "months": range(1, 13)
                                 , "ar_values": ar_values
                                 , "year": year
                                 , "year_prev": year_prev
                                 , "year_next": year_next
                                 }
                              , context_instance = RequestContext(request))

        
def get_archive_perf(request):
    items = ArchivePerf.objects.order_by("month").order_by("-year")
    ar_years = {}
    
    # Loop all items and store in matrix year => values for each month
    for ap in items:
        if ar_years.has_key(ap.year):
            ar_years[ap.year][ap.month - 1] = "%.14g" % ap.value
        else:
            ar_years[ap.year] = ["%.14g" % ap.value, "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"]
            
    lines = []
    for year in ar_years.keys():
        lines.append("\"%s\":[%s]" % (year, ",".join(ar_years[year])))

    callback = request.GET.get("callback")

    body = ",".join(lines)
    
    if callback != None:
        body = "%s({%s})" % (callback, body)
    else:
        body = "{%s}" % body
    
#    return HttpResponse(body, content_type="application/json")
    return HttpResponse(body, content_type="text/html")

@login_required
def import_deviations(request):
    form = MyUploadFileForm()
 
    if request.method == "POST":
        form = MyUploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            res = parse_and_import_deviations(request.FILES["file"])
            return HttpResponseRedirect("/pet/deviations/?%s" % res)

    return render_to_response(
                              "pet/importdeviations.html"
                              , {
                                 "form": form
                              }
                              , context_instance = RequestContext(request))

def parse_and_import_deviations(file):
    file_to_write = "%s%s" % (MEDIA_ROOT, file.name)
    print "MEDIA_ROOT: %s" % file_to_write
    fp = open(file_to_write, "wb+")
    for chunk in file.chunks():
        fp.write(chunk)
    fp.close()
    
    # Store Markets as dictionary to look by its name
    markets = get_markets_as_array()

    # Read stored file and parse it
    fp = open(file_to_write, "r")
    nr = 1
    total = 0
    imported = 0
    for line in fp.readlines():
#        print line
        if line.startswith("#") != True:
            ar = line.split('\t')
            if len(ar) > 5:
                print "Time is %s" % time.strftime("%Y-%M-%d", time.strptime(ar[0], "%M/%d/%Y"))
                market_name = ar[1].lower()
                if markets.has_key(market_name):
#                    try:
                        dt = time.strftime("%Y-%M-%d", time.strptime(ar[0], "%M/%d/%Y"))
#                        print dt
                        d = Deviation()
                        d.date = dt
                        d.market_id = markets[market_name]
                        d.category = ar[2]
                        d.initiator = ar[3]
                        d.pl_100 = ar[4]
                        d.note = ar[5]
                        d.save()
                        imported += 1
#                    except:
#                        print "Error saving Deviation on line %d!" % nr
                else:
                    print "No market name: %s!" % ar[1]
            else:
                print "Line %s has less than 5 elements!" % nr

    nr += 1
    return "total=%d&imported=%d" % (nr, imported)

def get_markets_as_array():
    ar = {}
    markets = Market.objects.all()
    for m in markets:
        ar[m.name.lower()] = m
    print "Markets as dictionary: %s" % ar
    return ar

def parse_daily_euro_conv_line(l):
    """ Parses tab-separated line to array """
    # Format is: day EURUSD, EURJPY, EURGBP, EURCHF, EURAUD, EURNZD, EURCAD
    row = [0, 0, 0, 0, 0, 0, 0, 0]
    f = ""
    try:
        ar = l.split("\t")
        if len(ar) > 7:
            row[0] = int(ar[0].strip(" \t."))
#            print "Day is: %d" % row[0]
            for i in range(1, 8):
                if len(ar[i].strip()) > 0:
                    row[i] = MyConstants.convert_string_to_decimal(ar[i])
        else:
            print "Length of line is (%d) less than 7!" % len(ar)
    except:
        print "Error parsing Euro conversion daily line: %s" % l
        
    return row

@permission_required(JrcPermission.PET_CHANGE, "/accounts/denied/")
def import_euro_conv_daily(request):
    
    if request.method == "POST":
        imported = 0
        total = 0
        form = EuroConvDailyUploadForm(request.POST, request.FILES)
        year = int(form["year"].value())
        month = int(form["month"].value())
        if form.is_valid():
            # Clear this month EUR conversion if form is valid
            EuroConvDaily.objects.filter(date__year = year).filter(date__month = month).delete()

            lines = form["textdata"].value().split("\n")
            for l in lines:
                if not l.startswith("#"):
                    row = parse_daily_euro_conv_line(l)
                    if row[0] != 0:
                        create_euro_conf(row, year, month)
            return HttpResponseRedirect("/pet/euroconv/daily/?year=%d&month=%d" % (year, month) ) #?imported=%d&total=%d" % (imported, total))
            
        # ENDI IF ( form.is_valid)
        
        

    else:
        form = EuroConvDailyUploadForm()
    
    return render_to_response("pet/importeuroconvdaily.html"
                                , {
                                   "form": form
                                }
                                , context_instance = RequestContext(request))

def create_euro_conf(row, year, month):
    ar_position = ["", "EURUSD", "EURJPY", "EURGBP", "EURCHF", "EURAUD", "EURNZD", "EURCAD"]
    if len(row) == 8:
        ec = EuroConvDaily()
        ec.date = "%d-%d-%d" % (year, month, row[0])
        
        try:
            existing = EuroConvDaily.objects.get(date = ec.date)
            print "Existing EuroConvDaily ID is %d" % existing.pk
            existing.delete()
        except EuroConvDaily.DoesNotExist:
            pass
        
        pos = ar_position.index("EURUSD")
        ec.EURUSD = row[pos]
        pos = ar_position.index("EURJPY")
        ec.EURJPY = row[pos]
        pos = ar_position.index("EURGBP")
        ec.EURGBP = row[pos]
        pos = ar_position.index("EURCHF")
        ec.EURCHF = row[pos]
        pos = ar_position.index("EURAUD")
        ec.EURAUD = row[pos]
        pos = ar_position.index("EURNZD")
        ec.EURNZD = row[pos]
        pos = ar_position.index("EURCAD")
        ec.EURCAD = row[pos]
        ec.save()
        print ec

        
@login_required
def archive_perf(request):
    current_year = datetime.datetime.now().year
    
    if request.method == "POST":
        year = request.POST.get("year")
    else:
        year = request.GET.get("year")
    print "Year from request: %s" % year
    if year != None:
        year = int(year)
    else:
        year = current_year
#    print "Year is %s" % year
    
    year_prev = year - 1
    year_next = 0
    # Whether it is possible to go next year
    if year <= current_year:
        year_next = year + 1 

    if request.method == "POST":
        ar_values = ArchivePerf.objects.filter(year = year)
        ar_values.delete()
        
        for m in range(1, 13):
            item = ArchivePerf()
            item.year = year
            item.month = m
            v = request.POST.get("v_%d" % m)
            print "Saving value: %s" % v
            
            try:
                item.value = Decimal(v)
            except (ValidationError, InvalidOperation):
                print "ERROR saving value [%s]" % v
                item.value = 0.0
            item.save()
        
        return HttpResponseRedirect("/pet/archiveperf?year=%d" % year)

    ar_values = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    ar = ArchivePerf.objects.filter(year = year).order_by("month")
    print "Default array: %s" % ar_values
    print "From DB: %s" % ar
    for i in ar:
        ar_values[i.month - 1] = i.value
    print ar_values
    
    return render_to_response(
                              "pet/archiveperf.html"
                              , {
                                 "months": range(1, 13)
                                 , "ar_values": ar_values
                                 , "year": year
                                 , "year_prev": year_prev
                                 , "year_next": year_next
                                 }
                              , context_instance = RequestContext(request))
        
@login_required
def euroconv(request):
    
    current_year = datetime.datetime.now().year
    
    ar_conv = {
              "01": [0, 0, 0, 0, 0, 0, 0]
              , "02": [0, 0, 0, 0, 0, 0, 0]
              , "03": [0, 0, 0, 0, 0, 0, 0]
              , "04": [0, 0, 0, 0, 0, 0, 0]
              , "05": [0, 0, 0, 0, 0, 0, 0]
              , "06": [0, 0, 0, 0, 0, 0, 0]
              , "07": [0, 0, 0, 0, 0, 0, 0]
              , "08": [0, 0, 0, 0, 0, 0, 0]
              , "09": [0, 0, 0, 0, 0, 0, 0]
              , "10": [0, 0, 0, 0, 0, 0, 0]
              , "11": [0, 0, 0, 0, 0, 0, 0]
              , "12": [0, 0, 0, 0, 0, 0, 0]
              }
    ar_headers = ["EURUSD", "EURJPY", "EURGBP", "EURCHF", "EURAUD", "EURNZD", "EURCAD"]
    
    if request.method == "POST":
        year = request.POST.get("year")
    else:
        year = request.GET.get("year")
    print "Year from request: %s" % year
    if year != None:
        year = int(year)
    else:
        year = current_year
#    print "Year is %s" % year
    
    year_prev = year - 1
    year_next = 0
    # Whether it is possible to go next year
    if year <= current_year:
        year_next = year + 1 

    # Select all conversions for specified year
    conversions = EuroConv.objects.filter(year = year).order_by("month")

    if request.method == "POST":
        # Clear old values
        conversions.delete()
        
        for m in "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12":
            c = EuroConv()
            c.year = year
            c.month = int(m)
            c.EURUSD = float( request.POST["v_%s[1]" % m] )
            c.EURJPY = float( request.POST["v_%s[2]" % m] )
            c.EURGBP = float( request.POST["v_%s[3]" % m] )
            c.EURCHF = float( request.POST["v_%s[4]" % m] )
            c.EURAUD = float( request.POST["v_%s[5]" % m] )
            c.EURNZD = float( request.POST["v_%s[6]" % m] )
            c.EURCAD = float( request.POST["v_%s[7]" % m] )
            c.save()
            print c
        return HttpResponseRedirect("/pet/euroconv?year=%d" % year)
    
    ec = EuroConv();
    ec.year = 2011
    ec.month = 1
    ec.EURUSD = 1.36950
    ec.EURJPY = 112.371
    ec.EURGBP = 0.85499
    ec.EURCHF = 1.29252
    ec.EURAUD = 1.37269
    ec.EURNZD = 1.77133
    ec.EURCAD = 1.37035
##    ec.save()
    
    for c in conversions:
        print c
        if c.month < 10:
            month = "0%d" % c.month
        else:
            month = str(c.month)
        ar_conv[month][0] = c.EURUSD
        ar_conv[month][1] = c.EURJPY
        ar_conv[month][2] = c.EURGBP
        ar_conv[month][3] = c.EURCHF
        ar_conv[month][4] = c.EURAUD
        ar_conv[month][5] = c.EURNZD
        ar_conv[month][6] = c.EURCAD
    return render_to_response(
                              "pet/euroconv.html"
                              , {
                                 "ar_conv": ar_conv
                                 , "ar_headers": ar_headers
                                 , "year": year
                                 , "year_prev": year_prev
                                 , "year_next": year_next
                                 }
                              , context_instance = RequestContext(request))
        
def get_euro_conv(request):
    year = request.GET.get("year")
    print "Year from request: %s" % year
    if year != None:
        year = int(year)
    else:
        year = datetime.datetime.now().year
#    print "Year is %s" % year
    
    # Select all conversions for specified year
    conversions = EuroConv.objects.filter(year = year).order_by("month")
    lines = []
    for c in conversions:
        print c
        lines.append('"%s": ["%s", "%s", "%s", "%s", "%s", "%s", "%s"]' % (c.month, c.EURUSD, c.EURJPY, c.EURGBP, c.EURCHF, c.EURAUD, c.EURNZD, c.EURCAD))

    body = "{%s}" % ",".join(lines)

    # Whether we should return JSON with Padding
    callback_name = request.GET.get("callback")
    if callback_name != None:
        body = "%s(%s)" % (request.GET.get("callback"), body)
    
    return HttpResponse(body, content_type = "text/html")

